package com.team.merchant.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

/**
 * WebSocket配置类
 */
@Configuration
@EnableWebSocketMessageBroker  // 启用WebSocket消息代理
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        // 设置消息代理的前缀，客户端订阅时使用
        // 客户端使用 /topic/stats 订阅消息
        registry.enableSimpleBroker("/topic");
        
        // 设置客户端发送消息的前缀
        // 客户端发送消息到 /app/xxx 时会路由到@MessageMapping("/xxx")注解的方法
        registry.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // 注册STOMP端点，支持原生WebSocket
        // 微信小程序只支持原生WebSocket，不支持SockJS
        registry.addEndpoint("/ws")
                .setAllowedOriginPatterns("*");  // 允许所有来源的跨域请求
        
        // 为Web浏览器提供SockJS支持
        registry.addEndpoint("/ws")
                .setAllowedOriginPatterns("*")
                .withSockJS();
    }
} 